package com.shz.appletsapi.service.webmagic;

import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.shz.appletsapi.common.support.GameType;
import com.shz.appletsapi.model.po.Game;

import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.processor.PageProcessor;


public class On91udRepoPageProcessor implements PageProcessor {

	private Site site = Site
			.me()
			.setRetryTimes(3)
			.setSleepTime(1000);
	
	private static String URL ="http://www.91ud.com/game/[\\d]*|\\s";

    @Override
    public void process(Page page) {
    	List<String> pages=page.getHtml().xpath("//div[@class='pagination']/a").links().all();
    	//pages.stream().forEach(System.out::println);
    	page.addTargetRequests(pages);
    	
    
    	if(page.getUrl().regex(URL).match()) {
    		//列表页	
    		List<String> details=page.getHtml().xpath("//a[@class='avatar']").links().all();
    		//details.stream().forEach(System.out::println);
        	page.addTargetRequests(details);	
    	}else {
    		//详情页
    		Game g =new Game();
    		g .setTitle(page.getHtml().xpath("//div[@class='name']/h1/text()").toString());
    	    g.setImageUrl(page.getHtml().xpath("//img[@class='avatar']//@src").toString());
    	    g.setTags(page.getHtml().xpath("//div[@class='tags']/allText()").toString());
    	    g.setType(GameType.getType(page.getHtml().xpath("//ul[@class='info']/li[1]/span[1]/strong/a/text()").toString()));
    		g.setArea(page.getHtml().xpath("//ul[@class='info']/li[1]/span[2]/strong/a/text()").toString());
    		g.setAuthor(page.getHtml().xpath("//ul[@class='info']/li[2]/span[1]/strong/text()").toString());
    	    g.setReleaseTime(page.getHtml().xpath("//ul[@class='info']/li[2]/span[2]/strong/text()").toString());
    		g.setSource(page.getHtml().xpath("//ul[@class='info']/li[3]/span[1]/strong/text()").toString());
    	    g.setClaim(page.getHtml().xpath("//ul[@class='info']/li[3]/span[2]/strong/text()").toString());
    	    g.setWxQrCode(page.getHtml().xpath("//div[@class='qrcode']/img[1]//@src").toString());
    	    g.setScreenshots(StringUtils.join(page.getHtml().xpath("//ul[@class='screenshot-list clearfix']").links().all(),","));
    	    g.setIntroduction(page.getHtml().xpath("//div[@class='description marked']/p/text()").toString());
    	    page.putField("game", g);
    	}
    	
    }

    @Override
    public Site getSite() {
        return site;
    }
}
